﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.IO;
using System.Threading;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.Management;
using System.Diagnostics;

using System.Web;
using System.Net.NetworkInformation;
using System.Reflection;

using System.Security.Cryptography;


namespace NetC
{
    public partial class NetC : Form
    {
        public NetC()
        {
            InitializeComponent();
        }

        //全局显示详细信息的变量
        public static InfoDetail mydetailform = null;
        enum MODE { EMPTY=0,CNATION = 1, CWORLD = 2, WNATION = 3, WWORLD = 4 };
        MODE mm = MODE.EMPTY;
        int rm_flag = 0;
        int check_flag = 0;

        //准备icon图标

        Icon icoNation = null;
        Icon icoWorld = null;
        Icon icoError = null;

        private void get_icoNation()
        {
            //获得正在运行类所在的名称空间 

            Type type = MethodBase.GetCurrentMethod().DeclaringType;

            string _namespace = type.Namespace;

            //获得当前运行的Assembly 

            Assembly _assembly = Assembly.GetExecutingAssembly();

            //根据名称空间和文件名生成资源名称 

            string resourceName = _namespace + ".icoNation.ico";

            //根据资源名称从Assembly中获取此资源的Stream 

            Stream stream = _assembly.GetManifestResourceStream(resourceName);

            icoNation = new Icon(stream);
        }

        private void get_icoWorld()
        {
            //获得正在运行类所在的名称空间 

            Type type = MethodBase.GetCurrentMethod().DeclaringType;

            string _namespace = type.Namespace;

            //获得当前运行的Assembly 

            Assembly _assembly = Assembly.GetExecutingAssembly();

            //根据名称空间和文件名生成资源名称 

            string resourceName = _namespace + ".icoWorld.ico";

            //根据资源名称从Assembly中获取此资源的Stream 

            Stream stream = _assembly.GetManifestResourceStream(resourceName);

            icoWorld = new Icon(stream);
        }



        private void get_icoError()
        {
            //获得正在运行类所在的名称空间 

            Type type = MethodBase.GetCurrentMethod().DeclaringType;

            string _namespace = type.Namespace;

            //获得当前运行的Assembly 

            Assembly _assembly = Assembly.GetExecutingAssembly();

            //根据名称空间和文件名生成资源名称 

            string resourceName = _namespace + ".icoError.ico";

            //根据资源名称从Assembly中获取此资源的Stream 

            Stream stream = _assembly.GetManifestResourceStream(resourceName);

            icoError = new Icon(stream);

        }

        private string get_check_message()
        {
            StringBuilder message = new StringBuilder("NetC：" + get_username() + "\n");

            if (get_ctype() == "2")
            {
                message.Append("连接：客户端-");
            }
            else
            {
                message.Append("连接：WEB-");
            }
            if (get_model() == "1")
            {
                message.Append("国内模式\n");
            }
            else
            {
                message.Append("国际模式\n");
            }

            string add = "http://10.0.0.55/user_info.php?uid=" + get_uid();
            string connecter = "";
            string str1 = post_data(add, connecter);
            if (str1 == str1.Replace("您已离线", ""))
            {
                message.Append("状态：NetC连接成功");
            }
            else
            {
                message.Append("状态：NetC连接断开");
            }

            return message.ToString();
        }

        public string srung_response(string code)
        {
            string[] codearray = code.Split(',');
            Regex myreg = new Regex(@"^\d{14}");
            if (myreg.IsMatch(codearray[0]) && codearray.Length !=3)
            {
                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey myname = mysoftware.OpenSubKey("NetC", true);
                myname.SetValue("UID", codearray[0]);
                code = "uid";
                //改变图标
                if (get_model() == "1") notifyIcon_info.Icon = icoNation;
                else notifyIcon_info.Icon = icoWorld;

            }
            else
            {
                if (codearray.Length == 3)
                {
                    int num_time = Convert.ToInt32(codearray[0]);
                    int hours = num_time / 3600;
                    int minutes = (num_time - hours * 3600) / 60;
                    int seconds = num_time - hours * 3600 - minutes * 60;

                    Int64 num_webin = Convert.ToInt64(codearray[1]);
                    Int64 num_webout = Convert.ToInt64(codearray[2]);

                    string re = "时长：" + hours.ToString() + "小时" + minutes.ToString() + "分" + seconds.ToString() + "秒\r"
                              + "入流量：" + (num_webin / 1024).ToString() + "KB\r"
                              + "出流量：" + (num_webout / 1024).ToString() + "KB";
                    //改变图标
                    if (get_model() == "1") notifyIcon_info.Icon = icoNation;
                    else notifyIcon_info.Icon = icoWorld;

                    return re;
                }

                if (codearray.Length == 0)
                {
                    codearray = code.Split('@');
                    notifyIcon_info.Icon = icoError;
                    code = codearray[0];
                }

            }
            /*
            Regex myreg = new Regex(@"^\d{14}");
            if (myreg.IsMatch(code))
            {
                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey myname = mysoftware.OpenSubKey("NetC", true);
                myname.SetValue("UID", code);
                code = "uid";

            }
             */ 
            switch (code)
            {
                case "user_tab_error":
                    {
                        return "认证程序未启动";
                    }
                case "username_error":
                    {
                        return "用户名错误";
                    }

                case "non_auth_error":
                    {
                        return "您无须认证，可直接上网";
                    }

                case "password_error":
                    {
                        return "密码错误";
                    }

                case "status_error":
                    {
                        return "用户已欠费，请尽快充值。";
                    }

                case "available_error":
                    {
                        return "用户已禁用";
                    }

                case "ip_exist_error":
                    {
                        return "用户已存在";
                    }

                case "usernum_error":
                    {
                        return "用户数已达上限";
                    }

                case "online_num_error":
                    {
                        return "该帐号的登录人数已超过限额\n如果怀疑帐号被盗用，请联系管理员。";
                    }

                case "mode_error":
                    {
                        return "系统已禁止WEB方式登录，请使用客户端";
                    }

                case "time_policy_error":
                    {
                        return "当前时段不允许连接";
                    }

                case "flux_error":
                    {
                        return "您的流量已超支";
                    }

                case "minutes_error":
                    {
                        return "您的时长已超支";
                    }

                case "ip_error":
                    {
                        return "您的IP地址不合法";
                    }

                case "mac_error":
                    {
                        return "您的MAC地址不合法";
                    }

                case "logout_ok":
                    {
                        return "登离成功。";
                    }
                case "logout_error":
                    {
                        return "登离失败。\n（可能您已经不在线上）";
                    }
                case "uid":
                    {
                        StringBuilder mymessage = new StringBuilder();

                        if (codearray.Length == 5)
                        {
                            if (HandleLimit(codearray[2]))
                            {
                                double liuliang = Convert.ToDouble(codearray[2]) / 1024 / 1024;

                                if (liuliang == 0)
                                {
                                    mymessage.Append("国际流量：无限制\n");
                                }
                                else
                                {

                                    mymessage.Append("国际流量：" + liuliang.ToString("0.00") + "MB\n");
                                }

                                liuliang = Convert.ToDouble(codearray[3]);
                                if (liuliang == 0)
                                {
                                    mymessage.Append("国内流量：无限制\n");
                                }
                                else
                                {
                                    mymessage.Append("国内流量：" + liuliang.ToString("0.00") + "MB\n");
                                }
                                
                            }
                            else
                            {

                                return " 连接断开。";
                            }
                            

                        }


                        return "登陆成功！" + "\n" + mymessage.ToString();  
                        
                    }

                default :
                    {
                        notifyIcon_info.Text = "NetC连接失败。";
                        notifyIcon_info.Icon = icoError;
                        return "发生错误：" + code ;
                    }
            }
        }

        public string get_username()
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software");
            RegistryKey myname = mysoftware.OpenSubKey("NetC");
            return myname.GetValue("username").ToString();
        }

        public string get_password()
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software");
            RegistryKey mypw = mysoftware.OpenSubKey("NetC");
            return mypw.GetValue("password").ToString();
        }

        public string get_mac()
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software");
            RegistryKey mymac = mysoftware.OpenSubKey("NetC");
            return mymac.GetValue("mac").ToString();
        }

        public string get_timeDiff()
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software");
            RegistryKey mytimediff = mysoftware.OpenSubKey("NetC");
            string value = mytimediff.GetValue("timeDiff").ToString();
            mytimediff.Close();
            mysoftware.Close();
            return value;
        }

        public void set_regValue(string name,string value)
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software",true);
            RegistryKey mytimediff = mysoftware.OpenSubKey("NetC",true);
            mytimediff.SetValue(name, value);
            mytimediff.Close();
            mysoftware.Close();
        }

        public string get_regValue(string name)
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
            RegistryKey subkey = mysoftware.OpenSubKey("NetC", true);
            if (subkey != null)
            {
                string str = subkey.GetValue(name).ToString();
                mysoftware.Close();
                return str;
            }
            return null;
        }


        public string GetNetCardMacAddress()
        {
            ManagementClass mc;
            ManagementObjectCollection moc;
            mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    return mo["MacAddress"].ToString();
                }

            }
            return "";
        }

        public string get_model()
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software");
            RegistryKey mypw = mysoftware.OpenSubKey("NetC");
            return mypw.GetValue("model").ToString();
        }

        public string get_ctype()
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software");
            RegistryKey mypw = mysoftware.OpenSubKey("NetC");
            return mypw.GetValue("ctype").ToString();
        }
        public string get_uid()
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software");
            RegistryKey mypw = mysoftware.OpenSubKey("NetC");
            return mypw.GetValue("UID").ToString(); 
        }

        public string get_localtime()
        {
            DateTime DateTime1970 = new DateTime(1970, 1, 1);
            TimeSpan time_local = DateTime.Now - DateTime1970;
            return ((int)time_local.TotalSeconds).ToString();
        }

        public string get_cversion()
        {
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software");
            RegistryKey mynetc = mysoftware.OpenSubKey("NetC");
            if (mynetc.GetValue("cversion") == null)
            {
                mynetc.Close();
                set_regValue("cversion", "13");             //set the initial version to be 13
                return "13";
            }
            else
            {
                return mynetc.GetValue("cversion").ToString();
            }
        }
 
        public string sign_in(string username, string password, string drop, string type)//drop 0 国际 ， 1 国内; type 1 web ，2 客户端
        {
            int n = 1;
            string login_add = "";
            string connecter = "";
            if (type == "1") //web登陆
            {
                n = Convert.ToInt32(get_regValue("wversion"));
                login_add = "http://" + get_regValue("wserver") + "/cgi-bin/do_login";//"http://10.0.0.55/cgi-bin/do_login";
                //md5 encode password
                MD5 MyMD5=MD5.Create();
               byte[] MD5Bytes = MyMD5.ComputeHash(Encoding.Default.GetBytes(password));
               StringBuilder MD5Builder = new StringBuilder();
               foreach (byte bt in MD5Bytes)
               {
                   MD5Builder.Append(bt.ToString("x2"));
               }
               password = MD5Builder.ToString().Substring(8, 16);
                //end of md5 encoding password
                connecter = "username=" + username + "&password=" + password + "&drop=" + drop + "&type=" + type + "&n=" + n.ToString();

                return post_data(login_add, connecter);


            }
            else
            {
                int key = 0;
                string _key = "";
                //username = HttpUtility.UrlEncode(username);
                string en_password = "";
                string en_mac = "";
                string mac = get_mac().ToLower();

                if (type == "2") //客户端登陆
                {
                    n = Convert.ToInt32(get_regValue("cversion"));
                    key = (Convert.ToInt32(get_localtime()) + Convert.ToInt32(get_timeDiff())) / 60;
                    _key = key.ToString();

                    //加密密码和mac地址
                    en_password = encrypt(password, _key);
                    en_mac = encrypt(mac, _key,false);

                    login_add = "http://"+ get_regValue("cserver") + ":" + get_regValue("cport") +"/cgi-bin/do_login";//"http://10.0.0.55:3333/cgi-bin/do_login";
                    ///////////////////////进行url编码/////////////////////////
                    en_password = HttpUtility.UrlEncode(en_password);
                    en_mac = HttpUtility.UrlEncode(en_mac);
                    ///////////////////////////////////////////////////////////
                    connecter = "username=" + username + "&password=" + en_password + "&drop=" + drop + "&type=" + type + "&n=" + n.ToString() + "&mac=" + en_mac;
                }

                string response = post_data(login_add, connecter);
                if (response.Split('@').Length > 1)
                {
                    string[] re_error = response.Split('@');
                    if (re_error[0] == "password_error")
                    {
                        int timefix = Convert.ToInt32(re_error[1]) - Convert.ToInt32(get_localtime());
                        set_regValue("timeDiff", timefix.ToString());

                        key = Convert.ToInt32(re_error[1]) / 60;//(Convert.ToInt32(get_localtime()) + Convert.ToInt32(get_timeDiff())) / 60;
                        
                        en_password = encrypt(password, key.ToString());
                        en_mac = encrypt(mac, key.ToString(),false);

                        ///////////////////////进行url编码/////////////////////////
                        en_password = HttpUtility.UrlEncode(en_password);
                        en_mac = HttpUtility.UrlEncode(en_mac);
                        ///////////////////////////////////////////////////////////
                        
                        connecter = "username=" + username + "&password=" + en_password + "&drop=" + drop + "&type=" + type + "&n=" + n.ToString() + "&mac=" + en_mac;
                        //尝试第二次post
                        response = post_data(login_add, connecter);
                    }
                }
                return response;
            }

        }


        public string sign_out(string UID,string type)
        {
            string loginout_add = null;
            if (type == "1")
            {
                loginout_add = "http://" + get_regValue("wserver") + "/cgi-bin/do_logout";
            }
            else
                if (type == "2")
                {
                    loginout_add = "http://" + get_regValue("cserver") + ":" + get_regValue("cport") + "/cgi-bin/do_logout";
                }

            //send data
           return post_data(loginout_add, "uid="+UID);
        }

        public string sign_force_logout()
        {
            string loginout_add = "http://" + get_regValue("wserver") + "/cgi-bin/force_logout";
            //send data
            string connecter = "username=" + tb_userneme.Text + "&password=" + tb_password.Text + "&drop=" + get_model() + "&type=1&n=1";
            return post_data(loginout_add, connecter);
        }

        public string keealive(string ctype,string UID)  //you can use this to check the log on time and so on
        {
             string add;
             if (ctype == "1")
                 add = "http://" + get_regValue("wserver") + "/cgi-bin/keeplive";
             else
                 add = "http://" + get_regValue("cserver") + ":" + get_regValue("cport") + "/cgi-bin/keeplive";
              return  post_data(add, "uid="+UID);

        }

        /*----------------------新的密码加密算法-------------------------------*/
        public string encrypt(string password, string key)
        {
            if (password.Length > 16)
            {

                password = password.Substring(0, 16);
            }
            int pw_len = password.Length;
            StringBuilder ret = new StringBuilder();

            for (int i = 0; i < pw_len; i++)
            {
                int _pass = Convert.ToInt32(password[i]);
                int _key = _get_keychar(key, i);
                _key = _key ^ _pass;
                ret.Append(_build_key(_key, i % 2));
            }

            return ret.ToString();
        }

        public string encrypt(string password, string key, bool checkLength)
        {
            if (checkLength)
            {
                password = password.Substring(0, 16);
            }
            int pw_len = password.Length;
            StringBuilder ret = new StringBuilder();

            for (int i = 0; i < pw_len; i++)
            {
                int _pass = Convert.ToInt32(password[i]);
                int _key = _get_keychar(key, i);
                _key = _key ^ _pass;
                ret.Append(_build_key(_key, i % 2));
            }

            return ret.ToString();
        }

        public int _get_keychar(string key, int num)
        {
            int len = key.Length;
            return Convert.ToInt32(key[len - num % len - 1]);
        }

        public string _build_key(int num, int reverse)
        {
            string ret = "";
            int _low = num & 0x0f;

            int _high = num >> 4;
            _high = _high & 0x0f;

            if (reverse == 0)
            {
                char temp1 = (char)(_low + 0x36);
                char temp2 = (char)(_high + 0x63);

                ret = temp1.ToString() + temp2.ToString();
            }
            else
            {
                char temp1 = (char)(_high + 0x63);
                char temp2 = (char)(_low + 0x36);

                ret = temp1.ToString() + temp2.ToString();
            }
            return ret;
        }

        /*-----------------------密码加密结束-----------------------------------*/



        public string post_data(string add, string connecter)
        {
            UTF8Encoding encoding = new UTF8Encoding();//utf8Encoding
            
            byte[] data = encoding.GetBytes(connecter);

            try
            {
                //post提交数据
                if (connecter.Length != 0) 
                {

                    //request
                    WebRequest myrequest = WebRequest.Create(add);
                    myrequest.Method = "POST";
                    myrequest.ContentType = "application/x-www-form-urlencoded";
                    myrequest.ContentLength = connecter.Length;

                    Stream mystream = myrequest.GetRequestStream();
                    //post data
                    mystream.Write(data, 0, data.Length);
                    mystream.Close();
                    //getresponse
                    HttpWebResponse myresponse = (HttpWebResponse)myrequest.GetResponse();

                    StreamReader reader = new StreamReader(myresponse.GetResponseStream(), Encoding.Default);
                    string re = reader.ReadToEnd();

                    return re;  //info
                }
                else //get 提交数据
                {

                    WebRequest myWebRequest = WebRequest.Create(add);
                    myWebRequest.Method = "get";

                    // Set the 'Timeout' property in Milliseconds.
                    myWebRequest.Timeout = 10000;

                    // This request will throw a WebException if it reaches the timeout limit before it is able to fetch the resource.
                    WebResponse myWebResponse = myWebRequest.GetResponse();
                    StreamReader reader = new StreamReader(myWebResponse.GetResponseStream(), Encoding.Default);
                    string re = reader.ReadToEnd();
                    return re;
                }

                //MessageBox.Show(re);
            }
            catch (Exception e)
            {
               return  e.Message;   //info
            }
        }

        public string passencode_in(string pw)
        {
            string pw2 = "";
            char temp;
            for (int i = 0; i < pw.Length; i++)
            {
                temp = (char)(pw[i] ^ 77);
                pw2 += temp;
            }
            return pw2;
        }


        public void show_info(string info)
        {
            NetConnection myform = new NetConnection();
            myform.label_info.Text = info;
            myform.scrollshow();
        }



/*--------------------------------------------------------------------------------------------------------------------*/



        private void re_name_CheckedChanged(object sender, EventArgs e)
        {
            tb_userneme.ReadOnly = false;
            if (tb_userneme.Text == "" && re_name.Checked == true)
            {
                re_name.Checked = false;
                MessageBox.Show("用户名不能为空。");
                
                
            }
            else
            {
                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey netconn = mysoftware.OpenSubKey("NetC",true);
                if (tb_userneme.Text != "" && re_name.Checked == false)
                {
                    netconn.SetValue("username", "");
                }
                else
                {
                    netconn.SetValue("username", tb_userneme.Text.ToString());
                }
                netconn.Close();
                mysoftware.Close();
                
            }
        }

        private void re_password_CheckedChanged(object sender, EventArgs e)
        {
            tb_password.ReadOnly = false;
            if (tb_password.Text == "" && re_password.Checked == true)
            {
                re_password.Checked = false;
                MessageBox.Show("密码不能为空。","出错了！",MessageBoxButtons.OK,MessageBoxIcon.Warning);

            }
            else
            {
                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey netconn = mysoftware.OpenSubKey("NetC", true);
                if (tb_password.Text != "" && re_password.Checked == false)
                {
                    netconn.SetValue("password", "");
                }
                else
                {

                    netconn.SetValue("password", passencode_in(tb_password.Text.ToString())); //对密码加密
                }
                netconn.Close();
                mysoftware.Close();
            }
        }

        private void NetC_Load(object sender, EventArgs e)
        {
            System.Diagnostics.Process[] kill_NETC = System.Diagnostics.Process.GetProcessesByName("NetC");
            if (kill_NETC != null)
            {
                int n = 0;
                foreach (System.Diagnostics.Process instance in kill_NETC)
                {
                    n++;
                }
                if (n > 1)
                {
                    MessageBox.Show("程序实例已经运行。", "警告——只能运行一个客户端", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.WindowState = FormWindowState.Minimized;
                    Application.Exit();
                   // this.Close();
                }
            }


            //准备图标
            get_icoError();
            get_icoNation();
            get_icoWorld();
            

            //judge if first run
            RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software",true);
            RegistryKey netconn = mysoftware.OpenSubKey("NetC",true);

            bool first_run = true;

                if ( netconn!=null && netconn.ValueCount == 13 + 2/*c w port*/ + 1/*latency*/ + 1 /*reminder*/ + 1 /*srun msg*/)
                {
                    first_run = false;
                }

            if (first_run == true)
            {
                HandleReg.resetReg();

                MessageBox.Show("欢迎使用BIT外网客户端。\r  By liudanking", "NetC", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                //check if mac changed
                if (netconn == null)
                {
                    netconn = mysoftware.CreateSubKey("NetC");
                    netconn.SetValue("mac", GetNetCardMacAddress());
                    mysoftware.Close();
                }

                //set usernamd and password to the TextBox
                tb_userneme.Text = get_username();
                tb_password.Text = passencode_in(get_password());
                //auto select
                if (tb_userneme.Text != "")
                {
                    re_name.Checked = true;
                    tb_userneme.ReadOnly = true;
                }
                else
                {
                    re_name.Checked = false;
                    tb_userneme.ReadOnly = false;
                }

                if (tb_password.Text != "")
                {
                    re_password.Checked = true;
                    tb_password.ReadOnly = true;
                }
                else
                {
                    re_password.Checked = false;
                    tb_password.ReadOnly = false;
                }



                if (get_model() == "1")
                {
                    model_nation.Checked = 国内模式ToolStripMenuItem.Checked = true;
                }
                else
                {
                    model_world.Checked = 国际模式ToolStripMenuItem.Checked = true;
                }

                if (get_ctype() == "2")
                {
                    客户端ToolStripMenuItem.Checked = true;
                }
                else
                {
                    wEB端ToolStripMenuItem.Checked = true;
                }


                //judge if hide
                if (tb_userneme.Text != "" && tb_password.Text != "")
                {
                    this.WindowState = FormWindowState.Minimized;
                    this.ShowInTaskbar = false;
                    this.Hide();
                    if (model_nation.Checked == true)
                        show_info("国内模式" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), get_ctype())));
                    else
                        show_info("国际模式" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), get_ctype())));
                
                }
            }
            timer_check.Interval = 10000;
            timer_check.Enabled = true;
            
        }

        private void model_nation_CheckedChanged(object sender, EventArgs e)
        {
            if (model_nation.Checked == true)
            {
                国内模式ToolStripMenuItem.Checked = true;
                国际模式ToolStripMenuItem.Checked = false;

                return;
            }
            else
            {
                国内模式ToolStripMenuItem.Checked = false;
                国际模式ToolStripMenuItem.Checked = true;
                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey netconn = mysoftware.OpenSubKey("NetC", true);
                netconn.SetValue("model", "0");
                netconn.Close();
                mysoftware.Close();
            }
        }

        private void model_world_CheckedChanged(object sender, EventArgs e)
        {
            if (model_world.Checked == true)
            {
                国内模式ToolStripMenuItem.Checked = false;
                国际模式ToolStripMenuItem.Checked = true;
                return;
            }
            else
            {
                国内模式ToolStripMenuItem.Checked = true;
                国际模式ToolStripMenuItem.Checked = false;
                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey netconn = mysoftware.OpenSubKey("NetC", true);
                netconn.SetValue("model", "1");
                netconn.Close();
                mysoftware.Close();
            }
        }

        private void btlogin_Click(object sender, EventArgs e)
        {
            string model,model_info;

            //hide the form and disable the latancy
            this.Hide();
            timer_latency.Enabled = false;

            if (tb_userneme.Text != "" && tb_password.Text != "")
            {
                if (model_nation.Checked == true)
                {
                    model = "1";
                    model_info = "国内模式";
                    国内模式ToolStripMenuItem.Checked = true;
                    国际模式ToolStripMenuItem.Checked = false;
                }
                else
                {
                    model = "0";
                    model_info = "国际模式";
                    国际模式ToolStripMenuItem.Checked = true;
                    国内模式ToolStripMenuItem.Checked = false;
                }

                if ( get_ctype() == "1")
                {
                        客户端ToolStripMenuItem.Checked = false;
                        //wEB_ToolStripMenuItem.Checked = false;
                        wEB端ToolStripMenuItem.Checked = true;
                }
                else
                {
                    客户端ToolStripMenuItem.Checked = true;
                    //wEB_ToolStripMenuItem.Checked = false;
                    wEB端ToolStripMenuItem.Checked = false;
                }
                //处理服务器返回信息
                show_info(model_info + srung_response(sign_in(tb_userneme.Text, tb_password.Text, model, get_ctype())));

            }
            else
                MessageBox.Show("用户名或密码错误。","出错了！", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }



        /*=====================================the menu function==================================*/
        private void ToolStripMenuItem_about_Click(object sender, EventArgs e)
        {
            MessageBox.Show("BIT网络登陆客户端\rVersion 1.3.0.2 (Build 20091130)\r E-mail: liudanking@gmail.com\rCopyRight (C) 2009 By HolyGroUp\n", "关于NetC", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
/*
        private void nation_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (get_model() == "1")
            {
                sign_out(get_uid(), get_ctype());
                show_info("国内模式" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, "1", get_ctype())));
            }
            else
            {
                国内模式ToolStripMenuItem.Checked = true;
                国际模式ToolStripMenuItem.Checked = false;

                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey myname = mysoftware.OpenSubKey("NetC", true);
                myname.SetValue("model", "1");
                sign_out(get_uid(), get_ctype());
                show_info("国内模式" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, "1", get_ctype())));
            }

            model_nation.Checked = true;
            model_world.Checked = false;
            notifyIcon_info.Text = "NetC";
        }

        private void world_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (get_model() == "0")
            {
                sign_out(get_uid(), get_ctype());
                show_info("国际模式" + srung_response(sign_in(tb_userneme.Text,tb_password.Text,"0",get_ctype())));
            }
            else
            {
                国内模式ToolStripMenuItem.Checked = false;
                国际模式ToolStripMenuItem.Checked = true;

                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey myname = mysoftware.OpenSubKey("NetC", true);
                myname.SetValue("model", "0");
                sign_out(get_uid(), get_ctype());
                show_info("国际模式" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, "0", get_ctype())));
            }
            model_world.Checked = true;
            model_nation.Checked = false;
            notifyIcon_info.Text = "NetC";
        }
        */
        private void 离线ToolStripMenuItem_Click(object sender, EventArgs e)
        {
           notifyIcon_info.Icon = icoError;
           show_info(srung_response(sign_out(get_uid(), get_ctype())));
        }

        private void 注销ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon_info.Icon = icoError;
            show_info((srung_response(sign_force_logout())));
        }

/*
        private void custom_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (get_ctype() == "2")
            {
                sign_out(get_uid(), get_ctype());
                show_info( "客户端" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), get_ctype())));
            }
            else
            {
                客户端ToolStripMenuItem.Checked = true;
                wEB端ToolStripMenuItem.Checked = false;
                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey myname = mysoftware.OpenSubKey("NetC", true);
                myname.SetValue("ctype", "2");
                sign_out(get_uid(), get_ctype());
                show_info("客户端" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), "2")));
            }
            notifyIcon_info.Text = "NetC";
        }

        private void wEB_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (get_ctype() == "1")
            {
                sign_out(get_uid(), get_ctype());
                show_info("WEB" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), get_ctype())));
            }
            else
            {
                客户端ToolStripMenuItem.Checked = false;
                wEB端ToolStripMenuItem.Checked = true;
                RegistryKey mysoftware = Registry.CurrentUser.OpenSubKey("software", true);
                RegistryKey myname = mysoftware.OpenSubKey("NetC", true);
                myname.SetValue("ctype", "1");
                sign_out(get_uid(), get_ctype());
                show_info("WEB" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), "1")));
            }
            notifyIcon_info.Text = "NetC";
        }
        */

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            show_info("本次登陆\n" + srung_response(keealive(get_ctype(), get_uid())) + "\n" + srung_response(sign_out(get_uid(), get_ctype())) + "\n再见！");

            this.Visible = false;
            this.ShowInTaskbar = false;
            this.notifyIcon_info.Visible = false;

            timer_main.Enabled = true;
        }

        private void bt_cancel_Click(object sender, EventArgs e)
        {
            show_info("本次登陆\n" + srung_response(keealive(get_ctype(),get_uid())) + "\n" + srung_response(sign_out(get_uid(), get_ctype())) + "\n再见！");

            this.Visible = false;
            this.ShowInTaskbar = false;
            this.notifyIcon_info.Visible = false;
            timer_main.Enabled = true;        
        }

        private void notifyIcon_info_MouseDoubleClick(object sender, MouseEventArgs e)
        {
                this.WindowState = FormWindowState.Normal;
                this.ShowInTaskbar = true;
                this.TopMost = true;
                this.Show();
        }

        private void NetC_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                this.Hide();
            }
        }

        private void timer_main_Tick(object sender, EventArgs e)
        {
            this.Close();
        }

        private void NetC_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal && timer_main.Enabled == false)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                this.Hide();
            }
            else
                e.Cancel = false;
        }

        private void 自服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string http_add = "http://10.0.0.55:8800/services1.php?checkid=9538&user_login_name=" + tb_userneme.Text +"&user_password=" + tb_password.Text;
            Process myprocess = new Process();

            string IEFileName = Environment.SystemDirectory;
            IEFileName = IEFileName.Substring(0, 2);
            IEFileName = IEFileName + @"\Program Files\Internet Explorer\iexplore.exe";
            myprocess.StartInfo.FileName = IEFileName;//"iexplore.exe";
            myprocess.StartInfo.Arguments = http_add;
            myprocess.Start();
        }

        private void 详细查询ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (mydetailform != null)
            {
                mydetailform.Close();
            }
            mydetailform = new InfoDetail();

            string add = "http://" + get_regValue("wserver") + "/user_info.php?uid=" + get_uid();
            string connecter = "";
            mydetailform.srun_flag = 0;
            mydetailform.Text = "查询详情";
            mydetailform.webBrowser_main.DocumentText = post_data(add, connecter);
            mydetailform.Show();
        }

        private void 简单查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            show_info(srung_response(keealive(get_ctype(), get_uid())));

        }

        private void 清空注册表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HandleReg.resetReg();
            MessageBox.Show("注册表清理完成！", "NetC", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void timer_check_Tick(object sender, EventArgs e)
        {
            if (check_flag == 0)
            {
                timer_check.Interval = 200708;//300000;
                check_flag = 1;
            }
            StringBuilder message = new StringBuilder("NetC：" + get_username() + "\n");
            if (get_ctype() == "2")
            {
                message.Append("连接：客户端-");
            }
            else
            {
                message.Append("连接：WEB-");
            }
            if (get_model() == "1")
            {
                message.Append("国内模式\n");
                notifyIcon_info.Icon = icoNation;
            }
            else
            {
                message.Append("国际模式\n");
                notifyIcon_info.Icon = icoWorld;
            }

            
            string add = "http://" + get_regValue("wserver") + "/user_info.php?uid=" + get_uid();
            string connecter = "";
            string str1 = post_data(add, connecter);
            //check 0 srun station info
            if (get_regValue("srunmsg") != DateTime.Now.Day.ToString())
            {
                mydetailform = new InfoDetail();
                mydetailform.srun_flag = 1;
                mydetailform.Text = "Srun3000站点通知";
                mydetailform.webBrowser_main.Navigate("http://" + get_regValue("wserver"));
                mydetailform.Show();
                set_regValue("srunmsg", DateTime.Now.Day.ToString());
            }
            //check 1
            if (rm_flag == 0)
            {
                rm_info myinfo = reminder.money_reminder(ref str1);
                if (myinfo.rm)
                {
                    notifyIcon_info.ShowBalloonTip(10000, myinfo.rm_str[0], myinfo.rm_str[1], ToolTipIcon.Info);
                }
                rm_flag = 1;
            }
            //check2
            if (/*str1 != str1.Replace("可用流量", "")*/str1.Contains("可用流量") && (!str1.Contains("未知")))
            {
                string yustr = str1.Substring(str1.LastIndexOf("可用流量"));
                //need to be modified
               // yustr = yustr.Substring(yustr.IndexOf("<p>") + 3, yustr.IndexOf("Byte") - yustr.IndexOf("<p>") - 3);
                //yustr = yustr.Substring(yustr.IndexOf("<p>") + 3, yustr.IndexOf("</p>") - yustr.IndexOf("<p>") - 4);
                ////
                //yustr.Replace("Bytes", "");
                int StartStr = yustr.IndexOf("<p>") + 3, LengthStr = yustr.IndexOf("Byte") - StartStr;
                if (LengthStr <= 0)
                {
                    sign_in(get_username(), passencode_in(get_password()), get_model(), get_ctype());
                    return;
                }
                else
                {
                    yustr = yustr.Substring(StartStr, LengthStr);
                }
                ////
                yustr = yustr.Replace(",","");
                if (yustr.Length>0 && HandleLimit(yustr))
                {
                    message.Append("Check@ " + DateTime.Now.ToLongTimeString() + " 连接成功");
                    //notifyIcon_info.Icon = icoNation;
                }
                else
                {
                    message.Append("Check@ " + DateTime.Now.ToLongTimeString() + " 流量禁用");
                    notifyIcon_info.Icon = icoError;
                }
            }
            else
            {
                if (get_regValue("exception") == "0")
                {
                    sign_in(get_username(), passencode_in(get_password()), get_model(), get_ctype());
                }
                else
                {                    
                    message.Append("Check@ " + DateTime.Now.ToLongTimeString() + " 连接断开");
                    notifyIcon_info.Icon = icoError;
                    notifyIcon_info.ShowBalloonTip(10000, "NetC连接检查", "时间：" + DateTime.Now.ToLongTimeString() + "\n状态：连接已断开", ToolTipIcon.Error);
                }
            }
             
            /*
            string result = keealive(get_ctype(), get_uid());
            if (result.Split(',').Length >= 3)
            {
                message.Append("Check@ " + DateTime.Now.ToLongTimeString() + " 连接成功");
                notifyIcon_info.Icon = icoOk;
            }
            else
            {

                message.Append("Check@ " + DateTime.Now.ToLongTimeString() + " 连接断开");
                notifyIcon_info.Icon = icoError;
            }
             */ 

            notifyIcon_info.Text = message.ToString();
        }

        private bool HandleLimit(string yuLiang)
        {
            if (get_model() == "0")
            {
                Int64 yuint = Convert.ToInt64(yuLiang);
                if (yuint == 0) return true;    //no limit
                yuint = yuint / 1024 / 1024;
                Int64 limitTh = Convert.ToInt64(get_regValue("limitTh"));
                if (yuint > limitTh)
                {
                    return true; //ok
                }
                else
                {
                    show_info(srung_response(sign_out(get_uid(), get_ctype())));
                    MessageBox.Show("已达到国际流量禁用阈值，连接已断开。", "NetC 国际流量保护", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    notifyIcon_info.Icon = icoError;
                    return false;
                }
            }
            return true;
        }



        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_setting myform = new Form_setting();
            myform.Show();
        }

        private void change_mode(object sender, EventArgs e)
        {
            ToolStripMenuItem mymenuitem = (ToolStripMenuItem)sender;
            string info;
            //judge the mode which to sign in
            if (mymenuitem.Text == "国内模式")
            {
                if (客户端ToolStripMenuItem.Checked)
                {
                    mm = MODE.CNATION;
                    info = "国内模式（客户端）。";
                }
                else
                {
                    mm = MODE.WNATION;
                    info = "国内模式（WEB端）。";
                }
            }
            else
                if (mymenuitem.Text == "国际模式")
                {
                    if (客户端ToolStripMenuItem.Checked)
                    {
                        mm = MODE.CWORLD;
                        info = "国际模式（客户端）。";
                    }
                    else
                    {
                        mm = MODE.WWORLD;
                        info = "国际模式（WEB端）。";
                    }
                }
                else
                    if (mymenuitem.Text == "客户端")
                    {
                        if (国内模式ToolStripMenuItem.Checked)
                        {
                            mm = MODE.CNATION;
                            info = "国内模式（客户端）。";
                        }
                        else
                        {
                            mm = MODE.CWORLD;
                            info = "国际模式（客户端）。";
                        }
                    }
                    else
                    {
                        if (国内模式ToolStripMenuItem.Checked)
                        {
                            mm = MODE.WNATION;
                            info = "国内模式（WEB端）。";
                        }
                        else
                        {
                            mm = MODE.WWORLD;
                            info = "国际模式（WEB端）。";
                        }
                    }
            timer_latency.Enabled = false;
            int latency = Convert.ToInt32(get_regValue("cmlatency"));
            if (latency > 0)
            {
                timer_latency.Interval = 1000 * latency;
                timer_latency.Enabled = true;

                //stop timer_check
                timer_check.Enabled = false;

                sign_out(get_uid(), get_ctype());
                string info_all = "将在" + latency.ToString() + "秒后切换到" + info;
                notifyIcon_info.ShowBalloonTip(latency * 500, "NetC模式切换信息", info_all, ToolTipIcon.Info);
                notifyIcon_info.Text = "NetC：模式切换延迟等待中……\n目标模式：" + info + "\n状态：您当前可以访问校内资源。";
            }
            else
            {
                //no latency ,change mode directly
                sign_out(get_uid(), get_ctype());
                timer_latency_Tick(sender, e);
            }
        }

        private void timer_latency_Tick(object sender, EventArgs e)
        {
            if (mm == MODE.EMPTY)
                return;
            if (mm == MODE.CNATION)
            {
                cluster_login(true, false, true, false);
            }
            else
                if (mm == MODE.CWORLD)
                {
                    cluster_login(false, true, true, false);
                }
                else
                    if (mm == MODE.WNATION)
                    {
                        cluster_login(true, false, false, true);
                    }
                    else//WWORLD
                    {
                        cluster_login(false, true, false, true);
                    }

            timer_latency.Enabled = false;
        }

        private void cluster_login(bool nmode, bool wmode, bool ctype, bool wtype)
        {
            //start timer_check
            timer_check.Enabled = true;

            model_nation.Checked = 国内模式ToolStripMenuItem.Checked = nmode;
            model_world.Checked = 国际模式ToolStripMenuItem.Checked = wmode;
            客户端ToolStripMenuItem.Checked = ctype;
            wEB端ToolStripMenuItem.Checked = wtype;
            if (nmode)
                set_regValue("model", "1");
            if (wmode)
                set_regValue("model", "0");
            if (ctype)
                set_regValue("ctype", "2");
            if (wtype)
                set_regValue("ctype", "1");
            if (nmode)
                show_info("国内模式" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), get_ctype())));
            else
                if (wmode)
                    show_info("国际模式" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), get_ctype())));
                else
                    if (ctype)
                    show_info("客户端" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), get_ctype())));
                    else
                        show_info("WEB端" + srung_response(sign_in(tb_userneme.Text, tb_password.Text, get_model(), get_ctype())));
            notifyIcon_info.Text = notify_info();
        }

        private string notify_info()
        {
             StringBuilder message = new StringBuilder("NetC：" + get_username() + "\n");
            if (get_ctype() == "2")
            {
                message.Append("连接：客户端-");
            }
            else
            {
                message.Append("连接：WEB-");
            }
            if (get_model() == "1")
            {
                message.Append("国内模式\n");
            }
            else
            {
                message.Append("国际模式\n");
            }
            return message.ToString();
        }

    }
}
